package com.gitee.wsl.model.plugin

import com.gitee.wsl.api.Closeable
import com.gitee.wsl.model.Model
import com.gitee.wsl.prop.AttributeKey

abstract class ModelPluginInstance<TModel: Model<TModel>,PluginConfig,Builder:ModelPluginBuilder<TModel,PluginConfig,Builder>>(
     val key: AttributeKey<ModelPluginInstance<TModel,PluginConfig,Builder>>,
     val config: PluginConfig,
     open val body: Builder.() -> Unit
) : Closeable {

    var onClose: () -> Unit = {}

    fun install(scope: TModel) {
        val pluginBuilder = createBuilder(key, scope, config).apply(body)
        this.onClose = pluginBuilder.onClose
        pluginBuilder.hooks.forEach { it.install(scope) }
    }

    abstract fun createBuilder(key: AttributeKey<ModelPluginInstance<TModel,PluginConfig,Builder>>, scope: TModel, pluginConfig: PluginConfig):Builder
       //= ModelPluginBuilder(key, scope, pluginConfig)

    override fun close() {
        onClose.invoke()
    }
}
